import React, { useState, useRef, useEffect } from "react";
import {
  StyleSheet,
  View,
  TextInput,
  FlatList,
  TouchableOpacity,
  Image,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from "react-native";
import { useRouter } from "expo-router";
import { MaterialCommunityIcons } from "@expo/vector-icons";

import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { Colors } from "@/constants/Colors";
import { useColorScheme } from "@/hooks/useColorScheme";
import { AI_ASSISTANT, INITIAL_AI_MESSAGES } from "@/constants/AIAssistant";
import { IceBreaker } from "@/components/chat/IceBreaker";
import { chatAPI } from "@/services/chatAPI";
import { useAuth } from "@/contexts/AuthContext";

export default function AIAssistantChatScreen() {
  const router = useRouter();
  const colorScheme = useColorScheme();
  const tintColor = Colors[colorScheme ?? "light"].tint;
  const flatListRef = useRef(null);
  const { userToken } = useAuth();

  const [message, setMessage] = useState("");
  const [messages, setMessages] = useState(INITIAL_AI_MESSAGES);
  const [isTyping, setIsTyping] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // 加载聊天历史
  useEffect(() => {
    if (userToken) {
      loadChatHistory();
    } else {
      setIsLoading(false);
    }
  }, [userToken]);

  // 加载聊天历史
  const loadChatHistory = async () => {
    try {
      setIsLoading(true);
      const response = await chatAPI.getConversation("ai-assistant");
      if (response.data && response.data.length > 0) {
        const formattedMessages = response.data.map((msg) => ({
          id: String(msg.id),
          text: msg.content,
          sender: msg.senderId ? "me" : "other",
          time: formatMessageTime(new Date(msg.createdAt)),
        }));
        setMessages(formattedMessages);
      }
    } catch (error) {
      console.error("Failed to load chat history:", error);
    } finally {
      setIsLoading(false);
    }
  };

  // 格式化消息时间
  const formatMessageTime = (date) => {
    return date.toLocaleTimeString([], {
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  // 自动滚动到底部
  useEffect(() => {
    if (flatListRef.current && messages.length > 0) {
      setTimeout(() => {
        flatListRef.current.scrollToEnd({ animated: true });
      }, 100);
    }
  }, [messages]);

  // 发送消息到AI助手
  const sendMessageToAI = async (content) => {
    setIsTyping(true);

    try {
      const response = await chatAPI.sendAIMessage(content);
      // const response=await chatAPT.
      if (response && response.data) {
        const { userMessage, aiResponse } = response.data;

        // 添加AI回复到消息列表
        const newAIMessage = {
          id: String(aiResponse.id),
          text: aiResponse.content,
          sender: "other",
          time: formatMessageTime(new Date(aiResponse.createdAt)),
        };

        setMessages((prev) => [...prev, newAIMessage]);
      }
    } catch (error) {
      console.error("Failed to send message to AI:", error);
      // 如果API调用失败，添加一个错误消息
      const errorMessage = {
        id: String(Date.now()),
        text: "抱歉，我暂时无法回复您的消息。请稍后再试。",
        sender: "other",
        time: formatMessageTime(new Date()),
      };
      setMessages((prev) => [...prev, errorMessage]);
    } finally {
      setIsTyping(false);
    }
  };

  // 发送消息
  const handleSend = async () => {
    if (message.trim() === "") return;

    const newMessage = {
      id: String(Date.now()),
      text: message,
      sender: "me",
      time: formatMessageTime(new Date()),
    };

    setMessages((prev) => [...prev, newMessage]);
    const sentMessage = message;
    setMessage("");

    // 发送消息到后端
    await sendMessageToAI(sentMessage);
  };

  // 处理从IceBreaker组件选择的消息
  const handleIceBreakerMessage = (selectedMessage: string) => {
    setMessage(selectedMessage);
  };

  // 渲染消息气泡
  const renderMessage = ({ item }) => {
    const isMe = item.sender === "me";

    return (
      <View
        style={[
          styles.messageContainer,
          isMe ? styles.myMessage : styles.otherMessage,
        ]}
      >
        {!isMe && <Image source={AI_ASSISTANT.avatar} style={styles.avatar} />}
        <View style={styles.messageWrapper}>
          <View
            style={[
              styles.messageBubble,
              isMe ? styles.myBubble : styles.otherBubble,
            ]}
          >
            <ThemedText style={[styles.messageText, isMe && { color: "#fff" }]}>
              {item.text}
            </ThemedText>
          </View>
          <ThemedText
            style={[
              styles.timeText,
              isMe ? styles.myTimeText : styles.otherTimeText,
            ]}
          >
            {item.time}
          </ThemedText>
        </View>
      </View>
    );
  };

  // 渲染正在输入指示器
  const renderTypingIndicator = () => {
    if (!isTyping) return null;

    return (
      <View style={[styles.messageContainer, styles.otherMessage]}>
        <Image source={AI_ASSISTANT.avatar} style={styles.avatar} />
        <View
          style={[
            styles.messageBubble,
            styles.otherBubble,
            styles.typingBubble,
          ]}
        >
          <View style={styles.typingIndicator}>
            <View style={[styles.typingDot, styles.typingDot1]} />
            <View style={[styles.typingDot, styles.typingDot2]} />
            <View style={[styles.typingDot, styles.typingDot3]} />
          </View>
        </View>
      </View>
    );
  };

  // 渲染加载指示器
  const renderLoading = () => {
    if (!isLoading) return null;

    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size='large' color={tintColor} />
        <ThemedText style={styles.loadingText}>加载聊天记录...</ThemedText>
      </View>
    );
  };

  return (
    <ThemedView style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity
          onPress={() => router.back()}
          style={styles.backButton}
        >
          <MaterialCommunityIcons
            name='arrow-left'
            size={28}
            color={tintColor}
          />
        </TouchableOpacity>
        <View style={styles.headerTitleContainer}>
          <ThemedText style={styles.headerTitle}>
            {AI_ASSISTANT.name}
          </ThemedText>
          <ThemedText style={styles.onlineStatus}>在线</ThemedText>
        </View>
        <TouchableOpacity style={styles.infoButton}>
          <MaterialCommunityIcons
            name='information-outline'
            size={28}
            color={tintColor}
          />
        </TouchableOpacity>
      </View>

      {/* AI辅助聊天破冰组件 */}
      <IceBreaker onSelectMessage={handleIceBreakerMessage} />

      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        style={styles.keyboardAvoidingView}
        keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0}
      >
        {renderLoading()}

        {!isLoading && (
          <FlatList
            ref={flatListRef}
            data={messages}
            renderItem={renderMessage}
            keyExtractor={(item) => item.id}
            contentContainerStyle={styles.messageList}
            ListFooterComponent={renderTypingIndicator}
          />
        )}

        <View style={styles.inputContainer}>
          <TextInput
            style={styles.input}
            value={message}
            onChangeText={setMessage}
            placeholder='输入消息...'
            placeholderTextColor='#999'
            multiline
          />
          <TouchableOpacity
            style={[
              styles.sendButton,
              !message.trim() && styles.sendButtonDisabled,
            ]}
            onPress={handleSend}
            disabled={!message.trim()}
          >
            <MaterialCommunityIcons
              name='send'
              size={24}
              color={message.trim() ? "#fff" : "#ccc"}
            />
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: "row",
    alignItems: "center",
    paddingTop: 60,
    paddingBottom: 15,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: "#E1E1E1",
  },
  backButton: {
    marginRight: 15,
  },
  headerTitleContainer: {
    flex: 1,
  },
  headerTitle: {
    fontSize: 20,
    fontWeight: "bold",
  },
  onlineStatus: {
    fontSize: 14,
    color: "#4CAF50",
  },
  infoButton: {
    marginLeft: 15,
  },
  keyboardAvoidingView: {
    flex: 1,
  },
  messageList: {
    paddingVertical: 15,
    paddingHorizontal: 10,
  },
  messageContainer: {
    flexDirection: "row",
    marginBottom: 15,
    alignItems: "flex-end",
  },
  myMessage: {
    justifyContent: "flex-end",
  },
  otherMessage: {
    justifyContent: "flex-start",
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
  },
  messageWrapper: {
    maxWidth: "70%",
  },
  messageBubble: {
    padding: 12,
    borderRadius: 18,
    marginBottom: 4,
  },
  myBubble: {
    backgroundColor: "#0a7ea4",
    borderBottomRightRadius: 4,
  },
  otherBubble: {
    backgroundColor: "#F0F0F0",
    borderBottomLeftRadius: 4,
  },
  messageText: {
    fontSize: 16,
    lineHeight: 22,
  },
  timeText: {
    fontSize: 12,
    color: "#999",
    marginTop: 2,
  },
  myTimeText: {
    textAlign: "right",
  },
  otherTimeText: {
    textAlign: "left",
  },
  inputContainer: {
    flexDirection: "row",
    padding: 10,
    borderTopWidth: 1,
    borderTopColor: "#E1E1E1",
    backgroundColor: "#fff",
  },
  input: {
    flex: 1,
    backgroundColor: "#F0F0F0",
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 10,
    maxHeight: 120,
    fontSize: 16,
  },
  sendButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: "#0a7ea4",
    justifyContent: "center",
    alignItems: "center",
    marginLeft: 10,
  },
  sendButtonDisabled: {
    backgroundColor: "#E1E1E1",
  },
  typingBubble: {
    paddingVertical: 14,
    paddingHorizontal: 20,
    minWidth: 70,
  },
  typingIndicator: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    height: 20,
  },
  typingDot: {
    width: 8,
    height: 8,
    borderRadius: 4,
    backgroundColor: "#999",
    marginHorizontal: 3,
  },
  typingDot1: {
    opacity: 0.4,
  },
  typingDot2: {
    opacity: 0.7,
  },
  typingDot3: {
    opacity: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  loadingText: {
    marginTop: 10,
    fontSize: 16,
    color: "#666",
  },
});
